package com.ruyuan.seckill.controller;

import com.alibaba.fastjson.JSON;
import com.ruyuan.seckill.cache.Cache;
import com.ruyuan.seckill.domain.enums.CheckedWay;
import com.ruyuan.seckill.domain.vo.TradeVO;
import com.ruyuan.seckill.exception.ServiceException;
import com.ruyuan.seckill.service.GoodsSkuManager;
import com.ruyuan.seckill.service.TradeManager;
import com.scholar.monitor.annotation.ScholarMonitor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 交易控制器
 */
@Api(description = "交易接口模块")
@RestController
@RequestMapping("/trade")
@Validated
@Slf4j
public class TradeBuyerController {

    /**
     * 交易管理器
     */
    @Autowired
    @Qualifier("tradeManagerImpl")
    private TradeManager tradeManager;
    /**
     * 商品SKU管理器
     */
    @Autowired
    private GoodsSkuManager goodsSkuManager;
    /**
     * 缓存操作组件
     */
    @Autowired
    private Cache cache;

    private final AtomicLong questTotal = new AtomicLong(0);

    private final AtomicLong successTotal = new AtomicLong(0);

    /**
     * 秒杀交易创建接口
     * @param client 客户端类型
     * @param way 购买方式
     * @param uid 用户id
     * @return 秒杀结果
     */
    @ApiOperation(value = "秒杀创建交易")
    @GetMapping(value = "/seckillCreate")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "client", value = "客户端类型", required = false, dataType = "String", paramType = "query", allowableValues = "PC,WAP,NATIVE,REACT,MINI"),
            @ApiImplicitParam(name = "way", value = "检查获取方式，购物车还是立即购买", required = true, dataType = "String", paramType = "query", allowableValues = "BUY_NOW,CART"),
    })
    @ScholarMonitor
    public Map<String, Object> secKillCreate(String client, String way, Integer uid) {
        log.info("秒杀抢购接口 入参 client {} way {} uid {}", client, way, uid);
        log.info("quest number:{}", questTotal.incrementAndGet());
        log.info("TradeBuyerController secKillCreate method  invoke");
        Map<String, Object> resultMap = new HashMap<>();
        TradeVO tradeVO = null;
        try {
            // 创建交易并基于LUA脚本扣减库存
            tradeVO = this.tradeManager.secKillCreate(client, CheckedWay.valueOf(way), uid);
            log.info("quest success number:{}", successTotal.incrementAndGet());
            resultMap.put("code", 0);
            resultMap.put("data", tradeVO);

            log.info("秒杀返回值为：{}", JSON.toJSONString(resultMap));

            return resultMap;
        } catch (IllegalArgumentException e) {
            log.error("秒杀出错 ", e);
        } catch (ServiceException e) {
            resultMap.put("code", e.getCode());
            resultMap.put("msg", e.getMessage());
        }

        return resultMap;
    }

}
